package com.exercises;

import com.alibaba.fastjson.JSONObject;
import netscape.javascript.JSObject;

import java.util.*;

class Exercise762 {
    public static void main(String[] args) {
        System.out.println(new Exercise762().countOfAtoms("Be32"));

    }

    private Integer target;
    private int maxIdx;


    public String countOfAtoms(String formula) {
        target = new Integer(0);
        maxIdx = formula.length() - 1;
        Map<String, Integer> map = dfs(formula);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Integer> e : map.entrySet()) {
            sb.append(e.getKey());
            if (e.getValue() > 1) {
                sb.append(e.getValue());
            }
        }
        return sb.toString();
    }

    public Map<String, Integer> dfs(String formual) {
        Map<String, Integer> map = new TreeMap<>();
        StringBuilder tempStr = new StringBuilder();
        Map<String, Integer> tempMap = new TreeMap<>();
        Integer tempNum = null;
        for (; target <= maxIdx; target++) {
            char c = formual.charAt(target);
            if (Character.isLowerCase(c)) {
                tempStr.append(c);
                continue;
            }
            if (Character.isDigit(c)) {
                int num = c - '0';
                tempNum = tempNum == null ? num : tempNum * 10 + num;
                continue;
            }
            tempNum = tempNum == null ? 1 : tempNum;
            if (tempStr.length() > 0) {
                String key = tempStr.toString();
                map.put(key, map.getOrDefault(key, 0) + tempNum);
            }
            if (tempMap.size() > 0) {
                for (Map.Entry<String, Integer> e : tempMap.entrySet()) {
                    map.put(e.getKey(), map.getOrDefault(e.getKey(), 0) + e.getValue() * tempNum);
                }
            }
            tempMap.clear();
            tempStr = new StringBuilder();
            tempNum = null;
            if (Character.isUpperCase(c)) {
                tempStr.append(c);
                continue;
            }
            if ('(' == c) {
                target++;
                tempMap = dfs(formual);
            }
            if (')' == c) {
                return map;
            }
        }

        tempNum = tempNum == null ? 1 : tempNum;
        if (tempStr.length() > 0) {
            String key = tempStr.toString();
            map.put(key, map.getOrDefault(key, 0) + tempNum);
        }
        if (tempMap.size() > 0) {
            for (Map.Entry<String, Integer> e : tempMap.entrySet()) {
                map.put(e.getKey(), map.getOrDefault(e.getKey(), 0) + e.getValue() * tempNum);
            }
        }
        return map;
    }
}